package yeepay

import (
	"context"
	"errors"
	"github.com/yop-platform/yop-go-sdk/yop/client"
	"github.com/yop-platform/yop-go-sdk/yop/constants"
	"github.com/yop-platform/yop-go-sdk/yop/request"
	"simplifly-tech/payment/consts"
	model2 "simplifly-tech/payment/model"
	"strconv"
)

func (yeePayService *YeePayService) Pay(ctx context.Context, payData *model2.PayData) (*model2.PaymentResponse, error) {
	if payData.Currency != "CNY" {
		return nil, errors.New("invalid currency ")
	}

	var priKey = request.IsvPriKey{Value: yeePayService.MchPrivateKey, CertType: request.RSA2048}
	var yopRequest = request.NewYopRequest(constants.POST_HTTP_METHOD, "/rest/v1.0/cashier/unified/order")

	yopRequest.AppId = yeePayService.AppKey
	yopRequest.IsvPriKey = priKey
	yopRequest.AddParam("parentMerchantNo", yeePayService.ParentMerchantNo)
	yopRequest.AddParam("merchantNo", yeePayService.ParentMerchantNo)
	yopRequest.AddParam("orderId", payData.OrderID+"-"+strconv.Itoa(int(payData.IncomeID)))
	yopRequest.AddParam("orderAmount", payData.Amount) //sysIncome.Paid
	yopRequest.AddParam("goodsName", payData.Title)
	yopRequest.AddParam("memo", payData.Body)

	if yeePayService.AggParam != "" {
		yopRequest.AddParam("aggParam", yeePayService.AggParam)
	}

	yeepayMap := map[consts.SysIncomeChannel]string{
		consts.SysIncomeChannelYeeAlipay:     "ALIPAY",
		consts.SysIncomeChannelYeeWeChatPay:  "WECHAT",
		consts.SysIncomeChannelYeeCreditCard: "YJZF",
		consts.SysIncomeChannelYeeDebitCard:  "YJZF",
	}
	if payData.Channel == consts.SysIncomeChannelYeeDebitCard {
		yopRequest.AddParam("cardType", "DEBIT") //借记卡
	}
	if payData.Channel == consts.SysIncomeChannelYeeCreditCard {
		yopRequest.AddParam("cardType", "CREDIT") //信用卡
	}
	limitPayType := yeepayMap[payData.Channel]
	yopRequest.AddParam("limitPayType", limitPayType)
	//yopRequest.AddParam("notifyUrl", SecureUrl("/notify/yeepay/flight/order/paid")) //TODO 回调传过来的
	yopRequest.AddParam("notifyUrl", payData.NotifyUrl)
	yopRequest.AddParam("returnUrl", payData.ReturnUrl)

	yopResp, err := client.DefaultClient.Request(yopRequest)
	if nil != err {
		return nil, err
	}

	Result := yopResp.Result.(map[string]interface{})
	if Result["code"] != "00000" {
		err = errors.New(Result["message"].(string))
		return nil, err
	}

	return &model2.PaymentResponse{
		OrderID:   payData.OrderID,
		YeePayUrl: Result["cashierUrl"].(string),
	}, nil
}
func (yeePayService *YeePayService) CancelPay(ctx context.Context, paymentID string) error {
	return nil
}
